package JUC;

import java.util.HashMap;
import java.util.concurrent.*;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLockDemo {

    public static void main(String[] args) {

        MyLock myLock = new MyLock();
        // 写
        for (int i = 1; i <= 5; i++) {
            final int tempInt = i;
            new Thread(() -> {
                myLock.write(tempInt + "", tempInt);
            }, String.valueOf(i)).start();
        }
        //读
        for (int i = 1; i <= 5; i++) {
            final int tempInt = i;
            new Thread(() -> {
                myLock.get(tempInt + "");
            }, String.valueOf(i)).start();
        }
    }
}

class MyLock {
    private volatile HashMap<String, Integer> map;
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public int get(String key) {
        readWriteLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + " 读取" + key);
            int i = map.getOrDefault(key, 0);
            System.out.println(Thread.currentThread().getName() + " 读取成功");
            return i;
        }catch (Exception e){
            e.printStackTrace();
            return -1;
        }finally {
            readWriteLock.readLock().unlock();
        }
    }

    public void write(String key, int value) {
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + " 写入" + key);
            map.put(key, value);
            System.out.println(Thread.currentThread().getName() + " 写入成功");
        }catch (Exception e){
            e.printStackTrace();
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }
}
